import { message } from 'antd';
import { nav, powerSensor, workshop } from '../services/navList';

export default {
  namespace: 'navList',

  // 状态机
  state: {
    navData: [], // "配电终端"导航树形菜单的数据
    navSelectedKey: '', // 当前"配电终端"的代码(code)
    sensorData: [], // 当前"配电终端"下的所有"监测节点"
    workshopData: [], // 当前"配电终端"下的所有"用电车间"
  },

  // 发起网络请求
  effects: {
    *getNav({ payload }, { call, put }) {
      const response = yield call(nav, payload);
      yield put({ type: 'callback_nav', response });
    },
    *getSensor({ payload }, { call, put }) {
      const response = yield call(powerSensor, payload);
      yield put({ type: 'callback_sensor', response });
    },
    *getWorkshop({ payload }, { call, put }) {
      const response = yield call(workshop, payload);
      yield put({ type: 'callback_workshop', response });
    },
    *updateSingle({ stateName, value }, { put }) {
      yield put({ type: 'callbackUpdate', stateName, value });
    },
  },

  // 回调处理
  reducers: {
    callback_nav(st, { response }) {
      const state = st;
      state.navData = response;
      return { ...state };
    },
    callback_sensor(st, { response }) {
      const state = st;
      if (response.success) state.sensorData = response.root;
      else if (response.status === 1) message.error(response.msg);
      return { ...state };
    },
    callback_workshop(st, { response }) {
      const state = st;
      if (response.success) state.workshopData = response.root;
      else if (response.status === 1) message.error(response.msg);
      return { ...state };
    },
    callbackUpdate(st, { stateName, value }) {
      const state = st;
      state[stateName] = value;
      return { ...state };
    },
  },
};
